import re
import timeit

# 测试数据
text = "Hello, this is a simple 123 string for testing regular expressions and simple string matching."
pattern = "\d+"

# 直接使用re.search()
def search_directly():
    return re.search(pattern, text) is not None

# 先编译正则表达式，然后使用
compiled_pattern = re.compile(pattern)
def search_with_compile():
    return compiled_pattern.search(text) is not None

# 使用timeit测量两种方法的时间
search_directly_time = timeit.timeit(search_directly, number=10000)
search_with_compile_time = timeit.timeit(search_with_compile, number=10000)

print(f"Direct search took: {search_directly_time:.6f} seconds")
print(f"Search with compile took: {search_with_compile_time:.6f} seconds")

""" 结果
Direct search took: 0.022326 seconds
Search with compile took: 0.009371 seconds
"""